﻿/*
* MetroPivot WebPart for SharePoint
* Version 1.0
* @requires jQuery v1.4.2 or greater - jQuery 1.7+ recommended
*
* Copyright (c) 2013 Chad Schroeder
* Home:
* http://metropivotwebpart.codeplex.com
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
/**
* @description MetroPivot WebPart for SharePoint
* @type jQuery
* @name MetroPivotWebPart
* @category Plugins/MetroPivotWebPart
* @author Chad Schroeder http://chadschroeder.blogspot.com
*/
;(function ($) {
    if ($ == null){
        return null;
    }

    var defaults = {
        changeDuration: 350,
        headerFontSize: "220%",
        uiDelay: 200,
        header: {
            headerOpacity: .3,
            headerSelector: function (item) { return item.children("h3").first(); },
            headersTemplate: function () { return $("<div class='mpwp_headers' />"); },
            headerItemTemplate: function () { return $("<span class='mpwp_header' />"); }
        },
        item: {
            itemSelector: function (item) { return item.children(".mpwp_pivot-item"); },
            pivotItemTemplate: function () { return $("<div class='mpwp_pivotItem' />"); },
            itemsTemplate: function () { return $("<div class='mpwp_items' />"); }
        },
        controlInitialized: undefined,
        selectedItemChanged: undefined,
        selectedItemBeforeChange: undefined
    };

    $.fn.pivotControl = function (settings) {
        if(this.length > 1){
            return this.each(function(index, e){ 
                $(e).pivotControl(settings); 
            });
        }

        $.extend(this, defaults, settings);
        $.extend(this,{
            animating : false,
            headers : undefined,
            items : undefined,
            
            goToItemByIndex:function(index){
                this.navigateTo(this.headers.children().eq(index));
            },
            goToItemByName:function(header){
                this.navigateTo(this.headers.children(":contains(" + header + ")").first());
            },
            navigateTo: function(e){
                if(this.animating){ 
                    return;
                }
                e.trigger("click");
            },
            goNext: function(){
                this.navigateTo(this.headers.children(".mpwp_current").next());
            },
            goPrevious: function(){
                this.navigateTo(this.headers.children(".mpwp_header").last());
            },

            initialize : function () {
                var $this = this, headers = this.header.headersTemplate(), items = this.item.itemsTemplate();

                $this.item.itemSelector($this).each(function (index, e) {
                    e = $(e);

                    var headElement = $this.header.headerSelector(e);
                    if (headElement.length == 0){
                        return;
                    }

                    var headerItem = $this.header.headerItemTemplate().html(headElement.html()).fadeTo(0, $this.header.headerOpacity).css({"display": "inline-block", "font-size": $this.headerFontSize}).attr("index", index).click(function() { 
                        $this.pivotClick($(this)); 
                    });

                    var pivotItem = $this.item.pivotItemTemplate().append(e).hide();

                    if (index == 0) {
                        headerItem.addClass("mpwp_current").css("opacity", 1);
                        pivotItem.addClass("mpwp_current").show();
                    }
                    
                    headers.append(headerItem);
                    items.append(pivotItem);

                    headElement.remove();
                });

                $this.append(headers).append(items);
                $this.headers = headers;
                $this.items = items;

                if($this.controlInitialized != undefined){
                    $this.controlInitialized();
                }

                return $this;
            },

            changeHeader: function(header, cb){
                var $this = this;

                $this.headers.children(".mpwp_header.mpwp_current").removeClass("mpwp_current").css("opacity", $this.header.headerOpacity);

                var animationElements = {
                    clones : header.addClass("mpwp_current").css("opacity",1).prevAll().clone(),
                    originals : $(header.prevAll().detach().toArray().reverse()).clone(true)
                };
                
                $("<span style=\"overflow: hidden;\"/>").append(animationElements.clones).prependTo($this.headers).animate({ "margin-left": "-" + header.prevAll().width() + "px", opacity: 0 }, $this.changeDuration, function () {
                    $(this).remove();

                    animationElements.originals.css("opacity", 0).appendTo($this.headers).fadeTo($this.uiDelay, $this.header.headerOpacity);
			
			        if (cb){
				        cb();
			        }
                });
                return $this;
            },

            changeView: function(item, index, cb){
                var $this = this;

                $this.items.children(".mpwp_pivotItem.mpwp_current").fadeOut("fast").removeClass("mpwp_current");

                setTimeout(function () {
		    
                    // move the item just out of view to the right
                    item.css({ marginLeft: $this.outerWidth(true), display: "", zoom: 1, opacity: 0}).animate( { marginLeft: 0, opacity: 1 }, $this.changeDuration, function() { 
			                item.addClass("mpwp_current");
                            if (cb){
                                cb(item);
			                }
		                });

                }, $this.uiDelay);                
            },

            viewBeforeChange: function(e) {
                var $this = this;
                if(typeof($this.selectedItemBeforeChange) == "function"){
                    $this.selectedItemBeforeChange(e);
                }
            },

            viewChanged: function(index, item) {
                var $this = this;
                if(typeof($this.selectedItemChanged) == "function"){
                    setTimeout(function(){
                        $this.selectedItemChanged(index, item);
                    });
                }
            },

            pivotClick : function (e) {
                // ignore if already current or still animating
                if (this.animating || e.is(".mpwp_current")){
                    return;
                }

                var done = 0, newItem = null, $this = this, index = e.attr("index"), item = $this.items.children(".mpwp_pivotItem:nth(" + index + ")"),currentItem = $this.items.children(".mpwp_current");
                
                if (currentItem.length > 0){
                    $this.viewBeforeChange({from: {index: currentItem.attr("index"), item: currentItem}, to: {index: index, item: item}});
                }

                $this.animating = true;
		        $this.wrap("<div class=\"mpwp_wrapper\" style=\"overflow: hidden; height: " + $this.outerHeight() + "px; width: " + $this.outerWidth() + "px\"></div>");
		        var unwrap = function(){
			        done++;
                    if (done >= 2){
				        setTimeout(function(){
                            item.queue(function(){
                                $this.unwrap();
                                $(this).dequeue();
                            });
                            try{
                                $this.viewChanged(index, item);
                            }
                            finally{
                                $this.animating = false;
                            }
                        });
			        }
		        };		

                // invoke change
                $this.changeHeader(e, unwrap).changeView(item, index, unwrap);
            },
        });

        if ($("#MetroPivotWebPart_CSS").length == 0){
            $("<style id=\"MetroPivotWebPart_CSS\" type='text/css'>"
                + ".mpwp_metro-pivot .mpwp_headers { white-space: nowrap; display: block; clear: both; } "
                + ".mpwp_metro-pivot .mpwp_pivot-item h3, .mpwp_metro-pivot .mpwp_headers .mpwp_header { font-weight: normal; display: inline-block; vertical-align: top; padding: 0; cursor: pointer; margin: 0px 10px 0px 2px; word-spacing: -3px; } "
                + ".mpwp_metro-pivot .mpwp_items { position: relative; } "
                + ".mpwp_metro-pivot .mpwp_items .mpwp_pivotItem { display: block; white-space: normal; text-align: justify; width: 100%; } "
                + ".mpwp_metro-pivot .mpwp_items .mpwp_pivotItem .mpwp_pivot-item { padding: 10px; } "
                + ".mpwp_header:hover { color: #0072bc; } "
                + ".s4-wpTopTable { visibility: hidden; } "
                + "</style>").appendTo("head");
        }

        return this.initialize();
    };
})(typeof(jQuery) == "undefined" ? null : jQuery);

;(function ($) {
    if ($ == null){
        return null;
    }

    var defaults = {
        retainTab: true,
        controlInitialized: undefined,
        selectedItemChanged: undefined
    };

    $.fn.metroPivotWebPart = function (settings) {
        if(this.length > 1)
        {
            return this.each(function(index, el){ $(el).metroPivotWebPart(settings); });
        }

        $.extend(this, defaults, settings);
        $.extend(this,{
            initialize : function () {
                try{

                    var container = this;
                    if (document.forms[0]
                        .elements["_wikiPageMode.value"] == "true" || document
                        .forms[0]
                        .elements["MSOLayout_InDesignMode"]
                        .value == "1") {
                            $(".s4-wpTopTable").css({visibility: "visible"});
                        return;
                    }

                    var wps = this.getWPSInZone($(container));
                    var html = "";
                
                    $(container).empty().addClass("mpwp_metro-pivot");
                    $(container).parents("table:eq(1)").before($(container).detach());
                    
                    $.each(wps, function(index, value) { 
                        var pivotItem = $("<div class=\"mpwp_pivot-item\"></div>");
                        pivotItem.append("<h3>" + value.title + "</h3>");
                        var content = pivotItem.append("<div></div>");
                        $(container).append(pivotItem);

                        if (value.body.find("div.ms-acal-header").length > 0){
                            //calendar alert!
                            var id = value.body.parents("td.s4-wpcell").attr("id");
                            var placeholder = $("<div class=\"mtro-cal-placeholder\"></div>").attr("data-cellID", value.body.parents("td.s4-wpcell").attr("id"));
                            pivotItem.css("padding", "0px");
                            content.append(placeholder);

                            $("#" + id + " .ms-WPHeader").css("display","none");
                            $("#" + id + " table.s4-wpTopTable").css({display: "inherit", visibility: "hidden"}).attr("data-cal", "1");;
                        } else {
                            content.append(value.body.children(":not(script)").detach());
                            
                            //script blocks move differently than other elements, jQuery bug
                            var scripts = value.body.children("script");
                            if (scripts.length > 0){
                                scripts.each(function(){
                                    content[0].appendChild(this);
                                });
                            
                            }
                        }
                    });


                    var p = $(container).pivotControl($.extend({
                        selectedItemChanged: function(index, item){ container.pivotIndexChanged(container, index, item);},
                        selectedItemBeforeChange: function(e){ container.pivotIndexBeforeChange(container, e);}
                        }, 
                        settings));

                    $(".s4-wpTopTable[data-cal!='1']").css({visibility: "visible"});

                    container.loadLastTab($(container).attr("id"), p);

                    if(this.controlInitialized != undefined){
                        this.controlInitialized();
                    }
                }
                catch(e){
                    $(".s4-wpTopTable").css({visibility: "visible"});
                }

            },

            pivotIndexBeforeChange: function(e, eFromTo){
                var calItem = eFromTo.from.item.find("div.mtro-cal-placeholder");
                if (calItem.length > 0){
                    $("#" + calItem.attr("data-cellID") + " table.s4-wpTopTable").css("visibility","hidden");//.slideUp("fast");
                }
            },

            pivotIndexChanged: function(e, index, item){
                //calendar check
                var calItem = item.find("div.mtro-cal-placeholder");
                if (calItem.length > 0){
                    var cellID = calItem.attr("data-cellID");
                    if (!calItem.data("metro-cal-init")){
                        $("#" + cellID + " .ms-WPHeader").css("display","none");
                        $("#" + cellID + " .ms-WPBorder").css("border","none");
                        $("#" + cellID + " .ms-PartSpacingVertical").css("display","none");
                        $("#" + cellID + " table.s4-wpTopTable").css("margin-top","-12px");
                        calItem.data("metro-cal-init", true);
                    }
                    $("#" + cellID + " table.s4-wpTopTable").css("visibility","visible");
                }

                if (this.retainTab){
                    document.cookie = e.attr("id") + "=" + index;
                }

                try{
                    this.adjustDialogSize(item);
                } 
                catch(e){
                    //ok to fail
                }
            },

            adjustDialogSize: function (item) {
                //resize dialog if we are in one
                var dlg = typeof(SP.UI.ModalDialog.get_childDialog) == "function" ? SP.UI.ModalDialog.get_childDialog() : null;
                if (dlg != null) {
                    var updateSizeAndPos = function(){
                        try{
                            dlg.$Q_0_orig = dlg.$Q_0;
                            try{
                                dlg.$Q_0 = function(a,b){
                                    var root = window;
                                    while(root.parent && root.parent!=null && root.parent != root){
                                        root=root.parent;
                                    }
                                    a = Math.min($(root).width() - 40, a);
                                    b = Math.min($(root).height() - 40, b);
                                    dlg.$Q_0_orig(a,b);
                                };
                                dlg.autoSize();
                            }
                            finally{
                                dlg.$Q_0 = dlg.$Q_0_orig;
                                dlg.$Q_0_orig = null;
                            }

                            setTimeout(function(){
                                var dlgWin = $(".ms-dlgContent:last", window.parent.document);
                                dlgWin.animate({ top: ($(window.top).height() / 2 - dlgWin.height() / 2) + "px", left: $(window.top).width() / 2 - dlgWin.width() / 2 });
                            });
                            
                        } catch(e){
                        }
                    };

                    if (item){
                        item.queue(function() {
                            try{
                                updateSizeAndPos();
                            } catch(e){
                                //
                            }    
                            $(this).dequeue();
                        });
                    }
                }
            },

            loadLastTab: function(id, e){
                if (this.retainTab){
                    var idx = document.cookie.match( '(^|;) ?' + id + '=([^;]*)(;|$)');
                    if (idx){
                        if (e.goToItemByIndex(Number(idx[2])))
                        {
                            return;
                        }
                    }
                } 

                var current = e.items.children(".mpwp_current");
                this.pivotIndexChanged(this, 0, current);
            },

            getWPSInZone: function(e){
                var zoneWps = [];
                var wps = $(e.parents("table:eq(1)")).find("h3.ms-WPTitle");
                var html = "";
                wps.each(function(index) {
                    var title =  $(this).text();
                    if (title.length > 0 && title.indexOf("(Hidden)") == -1){
                        var parentTable = $($(this).parents("table:eq(1)"));
                        parentTable.hide();
                        
                        zoneWps.push({title: title, body: parentTable.find("div.ms-wpContentDivSpace")});
                    }
                });

                return zoneWps;
            }
        });

        return this.initialize();
    };
})(typeof(jQuery) == "undefined" ? null : jQuery);